<?php
/*
 * QQ注册、邮箱注册部分公用函数
 * @Author:zhoug
 * @Date:2011-1-5
 */

/**
 * 发送激活账号的邮件
 * @param string $email
 * @param int  $uin
 * @return int 
 */
function send_qq_email_active($qq , $regFrom='' , $other = '' , $subject = '' , $body = '' , $active_url = ''){
	$active_num = Mcache::read(REG_QQ_ACTIVE_COUNT, $qq);
	if ($active_num > 2) return 2;
	
	//查临时库是否有这条信息
    $userInfo = bdb_sp_get_qqtemp($qq);
      if($userInfo === false){
      return 3;
    }

	$account = $userInfo['account'];
	$time = time();
	$key = '9R1Brkg7zYTrpksrgM7zmdUKodzDchSb';
	$token = md5($time . $qq . $key);
	if(empty($active_url))
	{
		$url = "http://www.xx5.com/register/index.php?a=qq_active_back&time=" .urlencode($time) ."&qq=" .urlencode($qq) ."&token=" .urlencode($token). "&other=" . urlencode($other) . '&from=' . urlencode($regFrom) ;
	}
	else 
	{
		$url = $active_url."&time=" .urlencode($time) ."&qq=" .urlencode($qq) ."&token=" .urlencode($token). "&other=" . urlencode($other) . '&from=' . urlencode($regFrom) ;
	}
	if(empty($subject))
	{
		$subject = '51新炫舞帐号激活邮件' ;
	}
	if(empty($body))
	{
		$body = '	<div style="font-size:14px;font-family:arial,verdana,sans-serif;line-height:23px;padding:0;margin:0; text-align: center">
					<div style="margin:0 auto; width:860px; padding:60px 0; text-align:left">
					<p style="margin:0 60px 23px 60px">亲爱的 '.$qq.' 您好，</p>
					<div style="background:#fffdd5; padding:30px 20px 30px 100px;margin:0 60px 25px 60px"><span style=" font-family:\'微软雅黑\',\'黑体\'; font-size:27px; font-variant:700; color:#F60; display: inline-block; width:280px; line-height:53px; vertical-align:top">感谢您注册51新炫舞，</span><a href="'.$url.'" target="_blank" style="background:#ff7e00; display:block; width:226px; height:53px; text-align:center; color:#FFF; font:700 16px/53px Arial; text-decoration:underline; display: inline-block;">请点这里完成帐号激活</a></div>
					<p style="font-weight:700;  padding:0 20px;margin:0 60px">完成帐号激活，您就可以来到我们五彩缤纷的炫舞世界！多变表情、搞怪道具、百变服饰、炫丽翅膀等你免费使用！
</p>
					<p style="margin:0 60px 23px 60px">马上激活吧，您可以直接点击下面的链接完成帐号激活：<br/><a href="'.$url.'" target="_blank">'.$url.'</a><br/><br />如果无法打开，可以将它复制到浏览器地址栏中。<br /><br/>此邮件由系统自动发送，请勿回复。</p>
					</div>
					</div>	';
	}
	$subject = iconv("UTF-8", "GB2312", $subject);	
	$body = iconv("UTF-8", "GB2312", $body);	
	
	if( send_mail($qq, $qq.'@qq.com', $subject , $body) ) {	
		// 增加操作次数		
		if($active_num)	{
			Mcache::increment(REG_QQ_ACTIVE_COUNT, $qq, 1);
		} else {
			Mcache::write(REG_QQ_ACTIVE_COUNT, $qq, 1,600);
		}
	
		//StatSetUserInfo('passport_qq_email_count', array("Account"=>$qq));//qq号发送邮件的次数 
		return 1;
	} else {
		return 0;
	}
}


function check_user_if_available($user){
	//判断密保，如果有绑定过不能注册
	if(spam_mail(OTHER_EMAIL_SERVICE_IP, FINDPASS_RUBLISH_EMAIL_PORT, $user.'@qq.com') == 1 || Transform_Email2Account($user.'@qq.com', $errorCode) != false ){
		return false;
	}
	return bdb_sp_check_qq_can_register($user);
}

function check_qq_rainbow_exist($qq,$pwd){//检查qq号跟彩虹号一样的时候密码是不是也一样
	$errorCode = '';
	$others = Transform_Goodid2Others($qq,$errorCode);
	if(is_array($others) && isset($others['uin'])){
		$errorCodes = '';
		$uin_others = Transform_Uin2Entire($others['uin'], $errorCodes);
		if($uin_others['pwd'] == md5($pwd)) return true;
	}
	return false;
}
/**
 * 保留号
 * @param unknown_type $account
 */
function CheckAccount($account) {
	$length = strlen($account);
	
    if($length < 5) return 1;
    if(in_array($account, array(12345,23456,34567,45678,56789,98765,87654,76543,65432,54321,43210,123456,234567,345678,456789,987654,876543,765432,654321,543210,1234567,2345678,3456789,9876543,8765432,7654321,6543210,12345678,23456789,98765432,87654321,76543210,123456789,987654321,876543210,9876543210))) return 2;
    if(preg_match('/^(\d)\1*$/', $account)) return 3;
    
    if($length == 5) {
    	if(preg_match('/^100/', $account)) return 4;	
    }
    if($length >= 6 && $length <=11) {
    		if(preg_match('/^(\d)\1*\d\1*$/', $account) || preg_match('/^\d(\d)\1*$/', $account)) return 5;	
    }
    return 0;
   
}
/**
 * 判断注册是否发邮件的号:回旋号 && 含有3个及以上连续数字的5位
 * @param $account
 */
function checkGoodAccount($account){
	if(strlen($account) == 5){
		if(preg_match('/(\d)\1{2}/', $account)) return true;	
	}
	$int = $account; 
	$ret = 0;
	while ($int > 1) {
		$ret = $ret * 10 + $int % 10;
		$int = $int / 10;
	}
	return $ret == $account ? 1:0;
}

 /**
  * 将email绑定到用户的密保中
  * @param $user
  * @param $email
  */
 function reg_bind_email_to_findpass($user, $email) {
 	$bind = addNewEmail($user, $email);
 	if($bind == false) return false;
 	$bind = bindEmail($user, $email);
 	if(!$bind)	return false;
 	$nBindFlag = getBindFlag($user);
	if (!($nBindFlag & 1)){
	    setBindFlag($user, 1);
    	$emailTip = substr_replace($email, '***', 0, 3);
	}
	return true;
 }	 
 
/**
 * 讲用户和email关联并生成一个唯一的key(作为绑定的依据)
 * 
 * @param string $user
 * @param string $email
 * @return key or false
 */
function addNewEmail($user, $email) {
	$code = md5(uniqid(rand(), true));
	$result = bdb_emailbind_add_email_list($user, $email, 0, $code);
	if(!$result) { //可能是已有该条记录
		$email_list_info = bdb_emailbind_get_email_list_info($user, $email);
		if(!is_array($email_list_info)) {
			return false;
		}
		$code = empty($email_list_info['code']) ?  $code : $email_list_info['code'];
		$result = bdb_emailbind_update_email_list($user, $email, 0, $code);
	}

	if ($result) { // 记录添加成功
		return $code;
	} else {
		return false;
	}
}

/**
 * 绑定email到用户
 * 
 * @param string $user
 * @param string $email
 * @return true or false
 */
function bindEmail($user, $email) {
	$email_list_info = bdb_emailbind_get_email_list_info($user, $email);
	if(!is_array($email_list_info)) {
		return false;
	}
	$code = $email_list_info['code'];
	
	$result1 = bdb_emailbind_update_email_list($user, $email, 1, $code);
	$result2 = bdb_emailbind_insert_bind_by_user($user, $email);
	$result3 = bdb_emailbind_insert_bind_by_email($user, $email);
	
	if ($result2 && $result3) { // 绑定操作成功
	    return true;
	} else {
		return false;
	}
}

function getBindFlag($sUser)
{
    //include_once $_SERVER['DOCUMENT_ROOT'] . '/fiveonelib/user/UserDataCenterPassPort.php';
    load_library('pub:user/UserDataCenterPassPort', false);	
    $aRet = UserDataCenterPassPort_Get($sUser, 'info_score_symbol');
    return intval(substr($aRet['info_score_symbol'], 6, 1));
}

/**
 * 设置绑定标志
 *
 * @param string $sUser 绑定的用户名
 * @param int $nValue 整数表示的用户绑定的情况(三bit表示 bit0:是否绑定email bit1:是否机密问题 bit2:是否设置绑定手机)
 * @param string $sOpt 操作标志 add:原来的基础上添加标志 del:删除相应的标志(不影响其他的)
 * @param bool
 */
function setBindFlag($sUser, $nValue, $sOpt='add')
{
   // require_once($_SERVER['DOCUMENT_ROOT'] . '/fiveonelib/user/UserDataCenterPassPort.php');
   load_library('pub:user/UserDataCenterPassPort', false);		
    $ret = UserDataCenterPassPort_Get($sUser, 'info_score_symbol');
    if ($ret === false)
    {
        $ret = UserDataCenterPassPort_Get($sUser, 'info_score_symbol');
    }
    if ($ret !== false)
    {
        $nBindBit = substr($ret['info_score_symbol'], 6, 1); //去第七位
        switch ($sOpt)
        {
            case 'add':
                $nSetFlagValue = $nBindBit | ($nValue & 7);
                break;
            case 'del':
                $nSetFlagValue = $nBindBit & (~($nValue & 7));
                break;
        }
        
        $sNewValue = substr($ret['info_score_symbol'], 0, 6) . $nSetFlagValue . substr($ret['info_score_symbol'], 7, 1);
        $ret = UserDataCenterPassPort_Update($sUser, array('info_score_symbol' => $sNewValue));
        if ($ret === false)
        {
            $ret = UserDataCenterPassPort_Update($sUser, array('info_score_symbol' => $sNewValue));
        }
    }
    return $ret;
}

 /**
  * 取得激活信息
  * @param $uin
  * @param $time
  * @param $email
  * @param $token
  * @return array
  */
function get_qq_active_info($time , $qq , $token, $regFrom , $other,$finalBackUrl=''){
		 $info['gourl'] = 'http://www.xx5.com/register/index.php';
 	     $info['msg'] = '对不起链接已失效，请登录 www.xx5.com 重新注册';
 	     if (!preg_match('/\d+/i' , $qq) || (md5($time . $qq . ACTIVE_KEY ) != $token) || (time() - 172800 > $time)) return $info;
 	     $other_utf = array();
 	      foreach (unserialize($other) as $key=>$value)
			{
				$other_utf[$key] = iconv('gbk', 'utf-8', $value);	
			} 
 	     /*
      		$other = unserialize($other);
			if(is_array($other) && array_key_exists('app_key', $other) && $other['app_key'] != '') {
				$app_key = $other['app_key'];
				$app_inviter = $other['app_inviter'];
				$app_token = $other['app_token'];
				if(md5($app_key . $app_inviter . 'BAeCp4iWqa1688Un') != $app_token)	{
					$info['msg'] = '错误的邀请';
 	     			return $info;
				}
			}
 	     */
 	     
 	     //查临时库是否有这条信息
 	     $userInfo = bdb_sp_get_qqtemp($qq); 	    
 	     if($userInfo === false){
			$info['gourl'] = 'http://www.xx5.com/default.htm';
 	     	$info['msg'] = '此帐号已经激活过了，请直接登录';
 	     	return $info;
 	     }
 	     //向用户库写记录
 	     $regIp = get_client_ip_from_ns(true);
 	     $password = $userInfo['pwd'];
 	     
 	     $return = bdb_sp_reg_qq_user($qq, $password, $regIp);	//插入Oracle用户库
 	     
 	     if(!is_array($return)){
 	     	$info['msg'] = '系统繁忙，请稍后再试';
 	     	return $info;
 	     }
 	     $uin = $return['uin'];
 	     $account = $return['account'];
 	     $goodid = $return['good_id'];
 	     if($account < 1) {
 	     	$info['msg'] = '系统繁忙，请稍后再试';
 	     	return $info;
 	     }
 	     
 	     //向用户信息库写记录 	 
 	    $regSex =  $userInfo['sex'];	
 	    $regSex_utf = iconv('gbk', 'utf-8', $regSex);
 	    $regAge = $userInfo['birth']; 	   
 	      $regProvince =  $userInfo['prov'];	
 	    $regTown = $userInfo['town'];	
 	    $regCity = $userInfo['city'];	
 	    $regEmail = '';
 	    $time  = $userInfo['regtime'];
 	    $regRealName = $userInfo['other']['realname'];
 	    $regCardId = $userInfo['other']['idcard'];
 	   
 	    insertMysql($account, $password, $regSex, $regAge, $regProvince, $regTown, $regCity, $regEmail, $time,$regRealName,$regCardId);   //插入Mysql用户信息库	 	   
 	   
 		if(!getBindUserByEmail($qq.'@qq.com')){	//查询指定email绑定的用户
 			if(!getBindUserByEmail($qq.'@qq.com')){	//再检验一次
 				if(!reg_bind_email_to_findpass($account, $qq.'@qq.com')) //绑定邮箱到密保
 				{
 	    	 		reg_bind_email_to_findpass($account, $qq.'@qq.com'); //再绑定一次
 				}
 			}
 	    }
	     
 		 $a = $account;
	     $b = time();
	     $c = md5($a . $b . $password);
	     $d = md5($a . $b . $c);
	     $e = 0;
	     if(!empty($finalBackUrl)){
	     	$url = $finalBackUrl.'&qq='.urlencode($qq).'&uin='.urlencode($uin).'&other='.urlencode(serialize($other_utf)) ;
	     }else{
	     	$url = 'http://www.xx5.com/register/index.php?a=regqq_suc&qq='.urlencode($qq).'&uin='.urlencode($uin).'&other='.urlencode(serialize($other_utf)) ;
	     }
	     $f = urlencode( $url );
	     $info['gourl'] = "http://passport.xx5.com/";
	     $info['msg'] = "恭喜，帐号激活成功！\\n\\n您可以使用QQ号： ". $qq ." 来登录51新炫舞。";
	     return $info;
}

/**
 * 查询指定email绑定的用户
 * @param string $email
 * @return string or false
 */
function getBindUserByEmail($email) {
	$result = bdb_emailbind_get_bind_info_by_email($email);
	if(is_array($result)) {
		return $result['user'];		
	} else {
		return false;
	}
}

function insertMysql($regUser, $password, $regSex, $regAge, $regProvince, $regTown, $regCity, $regEmail, $time,$regRealName='',$regCardId="") {
	$insert_mysql_array = array(
		'User_Password' 		=>	$password,
		'sex'					=>	$regSex,
		'byear'					=>	$regAge,
		'prov'					=>	$regProvince,
		'town'					=>	$regTown,
		'city'					=>	$regCity,
		'User_Email'			=>	$regEmail,
		'color'					=>	7,	
		'regdate'				=>	date('Y-m-d H:i:s', $time),
		'vip'					=>	0,
		'activate'				=>	1,
		'User_NewInfo'			=>	 substr(md5($regUser), 0, 4),
		'bmonth'				=>	'',
		'bday'					=>	'',
		'hiddenl'				=>	1,
		'hiddenp'				=>	1,
		'linktype'				=>	'qq',
		'music'					=>	'',
		'page'					=>	10001,
		'htemp2'				=>	getDefaultTemplete($regSex),
		'close'					=> 0,
        'Fimversion'			=> $time,
        'Fimservice_mask'		=> 0,
        'Fimsavemsg'			=> 0,
		'name'      => $regRealName,
    	'User_Auth' => $regCardId,
		'User_Load_Flag' => 2,
	);
	
	if(!BDBMemberCenterEngine_UpdateRows($regUser, $insert_mysql_array)) {	//将用户信息写入用户信息库，更新时不存在即插入
		BDBMemberCenterEngine_UpdateRows($regUser, $insert_mysql_array);	//重试一次
	}
}

function getDefaultTemplete($sex) {
	$default_tpl = array(3202,3191,3190,3185,3177,3162,3161,3152,3144,3137,3113,3119,3111,2691,2754,2696,2927,2683,3072,2943,2931,2752,2737,2703,2698);
	$rand_key = array_rand($default_tpl);
	return '-' . $default_tpl[$rand_key];
	
	/*$sex = $sex != '女士' ? 'boy' : 'girl';
	return $sex == 'boy' ? -2632 : -2483;*
	
	/*$defaultTemplates['boy'] = array (
		-1744, -1939, -1944, -2009, -2023, -2035, -2137, -2194, -2215, -2380, -2401, -2458, -2461,
		-2479, -2484, -2489, -2490, -2491, -2492
	);
	$defaultTemplates['girl'] = array (
		-1212, -1618, -1691, -1814, -1971, -2014, -2045, -2087, -2092, -2331, -2359, -2395, -2399,
		-2402, -2469, -2471, -2483
	);
	$index = array_rand($defaultTemplates[$sex]);
	return $defaultTemplates[$sex][$index];
	*/
}

/**
 * 发送激活账号的邮件
 * @param string $email
 * @param int  $uin
 * @return int 
 */
function send_email_active($email, $uin = 0, $other = '' , $active_url = '' , $password=""){
	$uin = intval($uin);
	$active_num = Mcache::read(REG_EMAIL_ACTIVE_COUNT, $email);
	if ($active_num > 5) return 2;
	
	if($uin < 1)  {	//如果没有传入uin，则自己转
		$errorCode = 0;
		$account = Transform_Email2Account($email , $errorCode);
		if($account == false) return 0;
		$uin = Transform_Account2ID($account, $errorCode);
		if($uin == false) return 0;
	}
	
	$userInfo = Transform_Uin2Entire($uin, $error = null);
	if(!is_array($userInfo)) return 0;
	if($userInfo['from'] != 'disabled') return 3;
	if($userInfo['email'] != $email) return 0;
	
	$account = $userInfo['account'];
	$time = time();
	$key = '9R1Brkg7zYTrpksrgM7zmdUKodzDchsb';
	$token = md5($uin . $time . $email . $key . $other);
	if(empty($active_url))
	{
		$url = "http://www.xx5.com/register/index.php?a=email_active_back&time=".urlencode($time) ."&uin=" .urlencode($uin) ."&token=" .urlencode($token) ."&email=" .urlencode($email) . "&other=" . urlencode($other);
	}
	else 
	{
		$url = $active_url."&time=".urlencode($time) ."&uin=" .urlencode($uin) ."&token=" .urlencode($token) ."&email=" .urlencode($email) . "&other=" . urlencode($other);
	}

	if(empty($subject))
	{
		$subject = '51新炫舞帐号激活成功确认邮件' ;
	}
	if(empty($body))
	{
		$body = '	尊敬的《51新炫舞》用户您好！<br/>
<div style="text-indent:2em">
恭喜您注册成功！您的密码：'.$password.'<br/></div>
<div style="text-indent:2em">
请进入官网<a href="http://www.xx5.com/" target="_blank">http://www.xx5.com/</a><br/></div>
<div style="text-indent:2em">
如有任何疑问，我们的<a  href="http://b.qq.com/webc.htm?new=0&amp;sid=800082051&amp;eid=2188z8p8p8p8z8K8p8R8q&amp;o=www.xx5.com&amp;q=7"  target="_blank">企业QQ（800082051）</a>24小时为您服务<br/><br/>
</div>
此邮件由系统自动发送，请勿回复。
';
	}
	$subject = iconv("UTF-8", "GB2312", $subject);	
	$body = iconv("UTF-8", "GB2312", $body);	
						
	if(send_mail($account, $email, $subject , $body) ) {
		// 增加操作次数		
		if($active_num)	{
			Mcache::increment(REG_EMAIL_ACTIVE_COUNT, $email, 1);
		} else {
			Mcache::write(REG_EMAIL_ACTIVE_COUNT, $email, 1,600);
		}
		return 1;
	} else {
		return 0;
	}
}

 /**
  * 取得激活信息
  * @param $uin
  * @param $time
  * @param $email
  * @param $token
  * @return array
  */
function get_email_active_info($uin , $time , $email , $token, $other){
		 $info['gourl'] = 'http://www.xx5.com/default.htm';
 	     $info['msg'] = '链接错误或已过期，请重新发送激活邮件';
 	     $key = '9R1Brkg7zYTrpksrgM7zmdUKodzDchsb';
 	     if ((md5($uin . $time . $email . $key . $other) != $token) || (time() - 604800 > $time)) return $info; 	  	     
	 
		 $userInfo = Transform_Uin2Entire($uin, $error = null) ;
 	     if (!is_array($userInfo)) {
 	     	   	 $info['msg']  = '系统繁忙，请稍后再试!'; 
 	     		 return $info;
 	     }
 	     if($userInfo['from'] != 'disabled') {
 	     		$info['msg'] = '帐号已经激活，以后可通过此邮箱找回密码。';
 	     		return $info;
 	     }
 	     if (!bdb_sp_update_regfrom($uin, 'email')) { //激活
 	     		 $info['msg']  = '系统繁忙，请稍后再试!'; 
 	     		 return $info;
 	     }
 	     
 	     if(!reg_bind_email_to_findpass($userInfo['account'], $email)) //绑定邮箱到密保
 	     {
 	     	reg_bind_email_to_findpass($userInfo['account'], $email) ;	//再绑定一次
 	     }
 	     
 	     $account = $userInfo['account'];
	     
	     if(empty($other)) {	//有可能用户是在登录时发的激活邮件，没有邀请等相关其它信息，要到数据库中查询
	     	$other = getInviteInfoByRegUser($account);
	     } else {
	     	$other = unserialize($other);
	     }
	     $gourl = $other['gourl'];

//	     if(!empty($other['app_inviter'])) {
//	     	Invited_User_Add_ToFriends($account, $other['app_inviter']);
//	     }

 		 $a = $account;
	     $b = time();
	     $c = md5($a . $b . $userInfo['pwd']);
	     $d = md5($a . $b . $c);
	     $e = 0;
	     $url = $gourl == '' ? 'http://www.xx5.com/register/index.php?a=email_suc&type=1&email='.$email.'&uin='.urlencode($uin) : $gourl;
	     //$url = 'http://www.xx5.com/register/index.php?a=regqq_suc&qq='.urlencode($qq) ;
	     $f = urlencode( $url );
	     $info['gourl'] = "http://passport.51.com/go.5p?a=$a&b=$b&c=$c&d=$d&e=$e&f=$f";
	    
	   
	     //$info['msg'] = "恭喜，注册成功！\\n\\n您可以使用 ". $email ." 来登录51了。\\n小贴士：为保障账号安全，建议此邮箱不要公开在个人资料中。";
	     $info['msg'] = "帐号已经激活，以后可通过此邮箱找回密码。";
	     return $info;
}

function getInviteInfoByRegUser($regUser) {
    $data_source = array();
	$table_suffix = substr(md5($regUser), 0, 1);
	$data_source['host'] = 'user-incr.db.51com';
	$data_source['port'] = 3306;
	
	$data_source['user'] = 'unity';	//线上环境
	$data_source['pwd'] = 'PfAO6zyIfNIOzWBUnEYE'; //线上环境
	//$data_source['user'] = 'nbdevp';	//开发环境
	//$data_source['pwd'] = 't70svzub79c3'; //开发环境
	
	$data_source['db'] = 'recommend_user_list';
	$data_source['table'] = 'table_reg_user_list_' . $table_suffix;

	$handle = mysql_connect($data_source['host']. ':' . $data_source['port'], $data_source['user'], $data_source['pwd']);
	if($handle == false) $handle = mysql_connect($data_source['host']. ':' . $data_source['port'], $data_source['user'], $data_source['pwd']);
	if($handle == false) return array();
	mysql_select_db($data_source['db']);
	
	$query = "SELECT * FROM {$data_source['table']} WHERE reg_user = '{$regUser}' LIMIT 1";
	$result = mysql_query($query);
	if(mysql_num_rows($result) > 0) {
		$row = mysql_fetch_assoc($result);
		mysql_close();
		
		$app_inviter = $row['recommend_user'];
		$app_key = $row['reg_activate_url'];
		
		if($row['reg_source'] == 'app') {
			$app_token = md5($app_key . $app_inviter . 'BAeCp4iWqa1688Un');
			$gourl = "http://apps.51.com/ajax/apps_sort.php?app_key=$app_key&from=$app_inviter&token=$app_token&action=add&is_reg=1";
		} else {
			$gourl = $app_key;
		}

		return array('app_inviter'=>$app_inviter, 'gourl'=>$gourl);	
	} else {
		mysql_close();
		return array();
	}
}

/**
 * 验证帐号是否可以注册
 */
function checkUserExists($account)
{
	if(!$result = bdb_sp_check_user_exist($account))    //第一次获取不到就再试一次
	{
	   $result = bdb_sp_check_user_exist($account);
	}
	if($result === true)    //可以注册
	{
		return false;
	}
	return true;
}

/**
 * 验证邮箱是否可以注册
 *
 */
function checkEmailExists($email)
{
	if(!$result = bdb_sp_check_email_exist($email))
	{
		$result = bdb_sp_check_email_exist($email);
	}
	if($result === true)   //可以注册
	{
		$ret = bdb_emailbind_get_bind_info_by_email($email);
		if($ret===false){
			return false; //输入帐号可用
		}else{
			return true; //该邮箱已被注册为密保邮箱
		}
	}
	return true;
}

//验证码验证
function checkSecureNumber($identifier, $secureNum) {        
	$ServerAuthCode = strtolower(Mcache::read(MCACHE_XX5_PASSPORT, PASSPORT_AUHTCODE_PREFIX . $identifier));	//从memcache中取出验证码
	$secureNum = strtolower($secureNum);
	Mcache::delete(MCACHE_XX5_PASSPORT, PASSPORT_AUHTCODE_PREFIX . $identifier);		//删除验证码
	if ((isset($ServerAuthCode) && ($ServerAuthCode != $secureNum)) || ($ServerAuthCode === ''))
	{
		return false;
	}
	else 
	{
		return true;
	}
}

/**
 * 
 * 通过ip获取ip归属地
 * @param $ip
 */
function get_location_by_ip($ip)
{
	if(!preg_match("/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/", $ip)) {
		return '';
	}
	
	$ipAddr = new IpAddr();
	$ret = $ipAddr->get_address($ip);
	$ret = iconv("gb2312","utf-8",$ret);
	if($ret)
	{
		return $ret;
	}
	return '';	
	
}

/**
 * 发送邮件接口.
 * @param $email
 * @param $subject
 * @param $content
 */
function sendMail($email, $subject, $content) {
	$host = '10.11.13.185';
	$port = 51011;
	if(empty($email) || empty($subject) || empty($content)) {
		return false;
	}
	$content = "{$email}|{$subject}|{$content}";

	$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
	if (!$socket) {
		return false;
	}
	socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, array("sec" => 0, "usec" => 50000));
	$result = socket_connect($socket, $host, $port);
	if ($result) {
		socket_write($socket, $content, strlen($content));
	} else {
		return false;
	}
	socket_close($socket);
	return true;
}

/**
 * 页面调用发送邮件接口 Ajax
 * @param unknown_type $email
 */
function doSendEmail($email,$uin,$loginuser){
	if(empty($email) || empty($uin) || empty($loginuser)){
		return false;
	}
	
	$time = time();
	$array_email = array(
		'qq.com' => 'http://mail.qq.com',
		'163.com' => 'http://mail.163.com',
		'126.com' => 'http://mail.126.com',
		'yahoo.com.cn' => 'http://mail.yahoo.com.cn',
		'sohu.com' => 'http://mail.sohu.com',
		'sina.com' => 'http://mail.sina.com',
		'mail.51.com' => 'http://mail.51.com',
		'hotmail.com' => 'http://www.hotmail.com',
		'yahoo.cn' => 'http://mail.yahoo.cn',
		'live.com' => 'http://mail.live.com',
		'gmail.com' => 'http://www.gmail.com',
		'189.cn' => 'http://mail.189.cn',
		'tom.com' => 'http://mail.tom.com',
		'139.com' => 'http://mail.139.com',
		'china.com' => 'http://mail.china.com',
		'eyou.com' => 'http://mail.eyou.com',
		'yeah.net' => 'http://mail.yeah.net',
		'sml.com' => 'http://mail.sml.com',
		'56.com' => 'http://mail.56.com',
		'e165.com' => 'http://mail.e165.com',
		'sand.com.cn' => 'http://mail.sand.com.cn',
		'263.com' => 'http://mail.263.com',
		'zhuaxia.com' => 'http://mail.zhuaxia.com',
		'msn.com' => 'http://mail.msn.com',
		'sogou.com' => 'http://mail.sogou.com',
		'cyworld.com.cn' => 'http://mail.cyworld.com.cn',
		'17173.com' => 'http://mail.17173.com',
		'ku6.com' => 'http://mail.ku6.com',
		'91.com' => 'http://mail.91.com'
	);
	$data = array();
	$_email_name = explode("@",$email);
	$address = $array_email[strtolower($_email_name[1])];
	$_token = md5($uin.$email.$time);
	$url = "http://passport.xx5.com/bind/index.php?a=verifyemail&uin=".$uin."&email=".$email."&time=".$time."&code=".$_token;
	$subject = "验证51新炫舞保护邮箱";
	$content = "亲爱的朋友：</br>
			  您在".date('Y-m-d')."为帐号".$loginuser."设置该邮箱为保护邮箱，请点击一下链接验证您的保护邮箱(验证后，可以通过保护邮箱找回丢失的密码)：</br>
			  <a href='".$url."' target='_blank'>点击验证您的保护邮箱</a>（本链接有效期为48小时，并且点击一次后失效）</br>
			  如果文字链接无效，您可以复制以下链接，粘贴到浏览器地址，然后按“回车“键验证您的保护邮箱</br>
			  ".$url."</br>
			  温馨提示：</br>
			  如果您没有发送此邮件，可能是其他用户误填了您的邮箱，请忽略此邮件</br>
			  本邮件为系统自动发出，请勿直接回复</br>
			  如有任何疑问，欢迎联系51新炫舞客服中心，企业QQ：800082051</br>";
	if(bdb_emailbind_get_email_list($uin,$email)){
		sendMail($email, $subject, $content);
		return $address;
	}elseif(bdb_emailbind_insert_email_list($uin,$email,'')){
		sendMail($email, $subject, $content);
		return $address;
	}else{
		return false;
	}
}